package controller

import (
	"net/http"
	"strconv"

	"myginproject/internal/models" // 更新导入路径

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type HuashuController struct {
	db *gorm.DB
}

func NewHuashuController(db *gorm.DB) *HuashuController {
	return &HuashuController{db: db}
}

// SearchDialogs 搜索对话
// @Summary 搜索对话内容
// @Description 根据关键词搜索对话内容，返回分页结果
// @Tags 对话管理
// @Accept json
// @Produce json
// @Param keyword query string true "搜索关键词"
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(10)
// @Success 200 {object} gin.H "{"chat_list": [], "pagination": {}}"
// @Router /api/dialogs/search [get]
func (c *HuashuController) SearchHuashu(ctx *gin.Context) {
	// 获取查询参数
	keyword := ctx.Query("keyword")
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	if keyword == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "搜索关键词不能为空"})
		return
	}

	// 验证分页参数
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 查询包含关键词的对话项
	var dialogLines []models.DialogLine
	lineQuery := c.db.Model(&models.DialogLine{}).
		Where("content LIKE ?", "%"+keyword+"%").
		Order("dialog_id, sequence") // 按对话ID和顺序排序

	// 获取总数
	var total int64
	if err := lineQuery.Count(&total).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询失败"})
		return
	}

	// 获取分页数据
	if err := lineQuery.Offset(offset).Limit(pageSize).Find(&dialogLines).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询失败"})
		return
	}

	// 收集对话ID
	dialogIDs := make([]int, 0)
	dialogIDMap := make(map[int]bool)
	for _, line := range dialogLines {
		if !dialogIDMap[line.DialogID] {
			dialogIDs = append(dialogIDs, line.DialogID)
			dialogIDMap[line.DialogID] = true
		}
	}

	// 查询完整的对话数据
	var dialogs []models.DialogContent
	if err := c.db.Preload("Lines", func(db *gorm.DB) *gorm.DB {
		return db.Order("dialog_lines2.sequence") // 确保对话项按顺序加载
	}).Where("id IN ?", dialogIDs).Find(&dialogs).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询失败"})
		return
	}

	// 转换数据格式，设置copy_num和hidden默认值
	for i := range dialogs {
		if dialogs[i].CopyNum == 0 {
			dialogs[i].CopyNum = 0 // 默认值，实际可以从其他字段获取
		}
		dialogs[i].Hidden = false // 默认值
	}

	// 构建响应
	response := gin.H{
		"chat_list": dialogs,
		"pagination": gin.H{
			"total":        total,
			"current_page": page,
			"page_size":    pageSize,
			"total_pages":  (int(total) + pageSize - 1) / pageSize,
		},
	}

	ctx.JSON(http.StatusOK, response)
}
